package com.swjd.type;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

//异步发送消息
public class Producer {
    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        //消息发送者（生产着)
        DefaultMQProducer producer = new DefaultMQProducer("group1");
        //发送给服务器地址
        producer.setNamesrvAddr("localhost:9876");
        //启动服务
        producer.start();
        //创建要发送的消息·
        for (int i = 1;i<13; i++) {
            String msg = ("这是第" + i + "条消息");
            Message message = new Message("topic3", "tag1", msg.getBytes());
            //发送异步消息
            producer.send(message, new SendCallback() {
                //发送成功的回调方法
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println(sendResult);
                }
                //发送失败的回调方法
                @Override
                public void onException(Throwable throwable) {
                    System.out.println(throwable);
                }
            });
            System.out.println("异步发送完成!");
        }
        //producer.shutdown();
    }
}
